package ru.kipriz.todoly.api.dao.http;

import ru.kipriz.todoly.api.Parser;
import ru.kipriz.todoly.api.dao.ItemDao;
import ru.kipriz.todoly.api.entities.ItemObject;

import java.io.IOException;
import java.util.List;

/**
 * <p>Copyright: Copyright (c) 2010</p>
 *
 * @author Andrey Volkov
 *         <br/>Date: 3/24/11
 */
public class ItemDaoHttp implements ItemDao {
    protected final Class<ItemObject> itemObjectClass = ItemObject.class;

    @Override
    public List<ItemObject> getAll() {
        try {
            String response = WebRequest.get("items.json");
            return Parser.parseListJson(itemObjectClass, response);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public ItemObject getItemById(long id) {
        try {
            String response = WebRequest.get("items/" + id + ".json");
            return Parser.parseJson(itemObjectClass, response);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public ItemObject createItem(ItemObject item, String... fields) {
        try {
            String response = WebRequest.post("items.json", Parser.toJson(item, fields));
            return Parser.parseJson(itemObjectClass, response);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public ItemObject deleteItem(long id) {
        try {
            String response = WebRequest.delete("items/" + id + ".json");
            return Parser.parseJson(itemObjectClass, response);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public ItemObject updateItem(ItemObject item, String... fields) {
        try {
            String response = WebRequest.post("items/" + item.getId() + ".json", Parser.toJson(item, fields));
            return Parser.parseJson(itemObjectClass, response);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
